package www.ym.com.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import www.ym.com.common.CustomException;
import www.ym.com.common.R;
import www.ym.com.dto.DishDto;
import www.ym.com.entity.Category;
import www.ym.com.entity.Dish;
import www.ym.com.entity.DishFlavor;
import www.ym.com.mapper.DishFlavorMapper;
import www.ym.com.mapper.DishMapper;
import www.ym.com.service.CategoryService;
import www.ym.com.service.DishFlavorService;
import www.ym.com.service.DishService;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private DishService dishService;


    /**
     * 新增菜品关联的口味
     *
     * @param dishDto
     */
    @Override
    public void saveWithFlavor(DishDto dishDto) {
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Dish::getName, dishDto.getName());
        int count = dishService.count(wrapper);
        if (count > 0) {
            throw new CustomException("菜品已存在");
        }
        dishDto.setStatus(1);
        this.save(dishDto);
        Long id = dishDto.getId();

        List<DishFlavor> itemList = dishDto.getFlavorItemList();
        log.info("itemList+"+itemList);
        itemList = itemList.stream().map((item) -> {
                    item.setDishId(id);
                    return item;
                }
        ).collect(Collectors.toList());
        dishFlavorService.saveBatch(itemList);
    }

    /**
     * 修改菜品
     *
     * @param dishDto
     */
    @Override
    public void updateWithFlavor(DishDto dishDto) {
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Dish::getName, dishDto.getName());
        int count = dishService.count(wrapper);
        if (count > 1) {
            throw new CustomException("菜品已存在");
        }
        this.updateById(dishDto);

        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId, dishDto.getId());
        dishFlavorService.remove(queryWrapper);

        Long id = dishDto.getId();
        List<DishFlavor> list = dishDto.getFlavorItemList();
        list = list.stream().map((item) -> {
            item.setDishId(id);
            return item;
        }).collect(Collectors.toList());
        dishFlavorService.saveBatch(list);
    }
}
